package com.example.lenovo.asia5b.home.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.bigkoo.pickerview.TimePickerView;
import com.example.lenovo.asia5b.home.bean.MyDataBean;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.SMSCode;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.example.lenovo.asia5b.util.StringUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.wushi.lenovo.asia5b.R.id.activity_write_user_data_birthday;
import static com.wushi.lenovo.asia5b.R.id.btn_verify_code;
import static com.wushi.lenovo.asia5b.R.id.txt_constell;

/**
 * 填写用户资料
 * Created by lenovo on 2017/7/8.
 */

public class WriteUserDataActivity extends BaseActivity implements ICallBack {
    private LoadingDalog loadingDalog;

    private EditText activity_write_user_data_username,activity_write_user_data_name,
            activity_write_user_data_email,activity_write_user_data_mobile;

    private long timeOut;
    private TimeCount timeCount;
    private String user_id;
    private UserBean user;

    private String phone;
    private MyDataBean beanHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_user_data);
        initView();
    }

    private void initView(){
        loadingDalog = new LoadingDalog(this);

        Intent intent = getIntent();
        user_id = intent.getStringExtra("user_id");

        F.id(R.id.activity_write_user_date_finish).clicked(this);//完成
        F.id(activity_write_user_data_birthday).clicked(this);//完成

        activity_write_user_data_username = findViewById(R.id.activity_write_user_data_username);//用户名
//        activity_write_user_data_nikename = findViewById(R.id.activity_write_user_data_nikename);//昵称
        activity_write_user_data_name = findViewById(R.id.activity_write_user_data_name);//姓名
        activity_write_user_data_email = findViewById(R.id.activity_write_user_data_email);//电子邮件
        activity_write_user_data_mobile = findViewById(R.id.activity_write_user_data_mobile);//手机

        F.id(btn_verify_code).clicked(this);//获取验证码
        F.id(R.id.activity_write_user_data_birthday).clicked(this);
        F.id(R.id.activity_login_phone_code).getEditText().addTextChangedListener(new EditChangedListener());
        if (!getIntent().hasExtra("register")) {
            activity_write_user_data_username.setFocusable(false);
            activity_write_user_data_username.setFocusableInTouchMode(false);
            myInfoData();
        }else {
            activity_write_user_data_mobile.setText(StringUtil.getMobilePhone((getIntent().getStringExtra("phone"))));
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.activity_write_user_date_finish://完成
                getPostAPI();
                break;
            case btn_verify_code://获取验证码
                phone = F.id(R.id.activity_write_user_data_mobile).getText().toString();
                if(!TextUtils.isEmpty(phone)){
                    loadingDalog.show();
                    SMSCode.getCode(this,phone);
                }else{
                    U.Toast(this,getResources().getString(R.string.sjhbnwk)
                    );
                }
                break;
            case R.id.activity_write_user_data_birthday://生日
                TimePickerView pvTime = new TimePickerView.Builder(WriteUserDataActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        String time = getTime(date2);
                        F.id(txt_constell).text(StringUtil.constell(WriteUserDataActivity.this,time));
                        F.id(activity_write_user_data_birthday).text(time);
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText(getResources().getString(R.string.qx))//取消按钮文字
                        .setSubmitText(getResources().getString(R.string.confirm))//确认按钮文字
                        .setContentSize(16)//滚轮文字大小
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setSubmitColor(ContextCompat.getColor(WriteUserDataActivity.this,R.color.wathet))//确定按钮文字颜色
                        .setCancelColor(ContextCompat.getColor(WriteUserDataActivity.this,R.color.wathet))//取消按钮文字颜色
                        .setLabel(getResources().getString(R.string.n),getResources().getString(R.string.y),getResources().getString(R.string.r),
                                getResources().getString(R.string.s),getResources().getString(R.string.f),"秒")
                        .isCenterLabel(false)
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
        }
    }



    /**
     * 调用修改资料接口
     */
    private void getPostAPI(){
        try{
            String username = activity_write_user_data_username.getText().toString();//用户名
//            String nickname = activity_write_user_data_nikename.getText().toString();//昵称
            String alias = activity_write_user_data_name.getText().toString();//姓名
            String email = activity_write_user_data_email.getText().toString();//电子邮件
            String mobile_phone = activity_write_user_data_mobile.getText().toString();//手机
            String birthday = F.id(activity_write_user_data_birthday).getText().toString();//生日
            String[] items = getResources().getStringArray(R.array.constellation);//星座
            String constellID = "1";//星座ID
            for (int i = 1; i < items.length; i++) {
                if (items[i].equals(F.id(txt_constell).getText().toString())){
                    constellID = i+"";
                    break;
                }
            }
            if (TextUtils.isEmpty(birthday)){
                U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.my_data_hint_7));
                return;
            }
            if (mobile_phone.indexOf("*")!=-1) {
                if (getIntent().hasExtra("phone")) {
                    mobile_phone =getIntent().getStringExtra("phone");
                }
            }

            if (!TextUtils.isEmpty(email)){
                if (!StringUtil.checkEmail(email)) {
                    U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.my_data_hint_3));
                    return;
                }
            }
            if (TextUtils.isEmpty(mobile_phone)){
                U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.my_data_hint_4));
                return;
            }
            if(!TextUtils.isEmpty(username)){
//                if(!TextUtils.isEmpty(nickname)){
//                    if(!TextUtils.isEmpty(alias)){
                        if(!TextUtils.isEmpty(email)) {
                            if (!StringUtil.isNumeric(username)) {
                                if (username.length()<3) {
                                    U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.yhmbnxy));
                                    return;
                                }
                                if (F.id(R.id.ll_phone).getView().getVisibility()== View.VISIBLE) {
                                    U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.bdzh));
                                    return;
                                }
                                loadingDalog.show();
                                user = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
                                if (null == user) {
                                    user = new UserBean();
                                }
                                if (getIntent().hasExtra("url")){
                                    user.avatar = getIntent().getStringExtra("url");
                                }
                                user.user_id = user_id;
                                user.user_name = username;
                                user.alias = alias;
                                user.email = email;

                                if (!TextUtils.isEmpty(mobile_phone)){
                                    user.mobile_phone = mobile_phone;
                                }
                                user.user_money = "0";
                                user.pay_points = "0";
                                if (null == beanHome){
                                    beanHome = new MyDataBean();
                                }
                                String myDataURL = Setting.PERFECT_INFO;
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("user_id", user_id);//用户id
                                map.put("user_name", username);//昵称
//                                map.put("nickname", nickname);//昵称
//                                map.put("alias", alias);//姓名
//                                map.put("sex", beanHome.sex);//性别
                                map.put("birthday", birthday);//生日
                                Resources res =getResources();
//                                String[] languages = res.getStringArray(R.array.constellation);
//                                String constell = "";
//                                for (int i = 0; i < languages.length;i++){
//                                    if (languages[i].equals(beanHome.constell)) {
//                                        constell = i+"";
//                                        break;
//                                    }
//                                }
                                map.put("constell", constellID);//星座
//                                map.put("live_country", beanHome.live_country_id);
//                                map.put("live_province", beanHome.live_province_id);
//                                map.put("home_country", beanHome.home_country_id);
//                                map.put("home_province", beanHome.home_province_id);
                                map.put("email", email);//邮件
//                                map.put("mobile_phone",mobile_phone);//手机

                                Date date = new Date();
                                String time = String.valueOf(date.getTime());
                                map.put("time", time);

                                String[] sortStr = {"user_id" + user_id,
                                        "birthday" + birthday, "constell" + constellID,
                                        "email" + email, "time" + time};
                                String sotr = Logic.sortToString(sortStr);
                                String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sotr));
                                map.put("sign", md5);

                                JsonTools.getJsonAll(this, myDataURL, map, 3);

                            } else {
                                U.Toast(this, getResources().getString(R.string.bncsz)
                                );
                            }
                        }
                        else{
                            U.Toast(this,getResources().getString(R.string.my_data_hint_2)
                            );
                        }
//                    }
//                    else{
//                        U.Toast(this,getResources().getString(R.string.my_data_hint_8));
//                    }
//                }else{
//                    U.Toast(this,getResources().getString(R.string.my_data_hint_1));
//                }
            }else{
                U.Toast(this,getResources().getString(R.string.yhmbnwk));
            }
        }catch (Exception e){
            Log.e("完善资料接口error：",e.getMessage());
            loadingDalog.dismiss();
            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.dysb));
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            Intent intent = null;
            try{
                if(result != null){
                    if(action == 3){
                        JSONObject jsonObject = (JSONObject)result;
                        String state = jsonObject.getString("State");
                        if(TextUtils.equals("0",state)){
                            SharedPreferencesUtils.setObjectToShare(user,"user");
                            intent = new Intent(WriteUserDataActivity.this,MainActivity.class);
                            if (getIntent().hasExtra("register")) {
                                intent.putExtra("register",getIntent().hasExtra("register"));
                            }
                            intent.putExtra("user_id",user_id);
                            finishAll();
                            startActivity(intent);
                            finish();
                        }else if(TextUtils.equals("1",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.qmsb));
                        }else if(TextUtils.equals("2",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.cscw));
                        }else if(TextUtils.equals("3",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.my_data_hint_8));
                        }else if(TextUtils.equals("4",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.yhmycz));
                        }else if (TextUtils.equals("5",state)) {
                            U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.yxycz));
                        }
                        loadingDalog.dismiss();
                    }
                  if (action == 1) {
                        if (null != result && result instanceof JSONObject) {
                            try {
                                JSONObject json = (JSONObject) result;
                                int state = (int) json.getInt("State");
                                if (state == 0) {
                                    JSONObject user_info = json.getJSONObject("user_info");
                                    beanHome = (MyDataBean) Logic.getBeanToJSONObject(user_info, new MyDataBean());

                                    String user_name = beanHome.user_name;
                                   F.id(R.id.activity_write_user_data_username).text(user_name);

//                                    String nickname = beanHome.nickname;
//                                    F.id(activity_write_user_data_nikename).text(nickname);

                                    String alias = beanHome.alias;
                                    F.id(R.id.activity_write_user_data_name).text(alias);


                                    String email = beanHome.email;
                                    F.id(R.id.activity_write_user_data_email).text(email);

                                    String mobile_phone = beanHome.mobile_phone;
                                    if (TextUtils.isEmpty(mobile_phone)){
                                        activity_write_user_data_mobile.setFocusable(true);
                                        activity_write_user_data_mobile.setFocusableInTouchMode(true);
                                        F.id(R.id.ll_phone).visibility(View.VISIBLE);
                                    } else {
                                        F.id(R.id.activity_write_user_data_mobile).text(StringUtil.getMobilePhone((mobile_phone)));
                                    }

                                    String constell = beanHome.constell;
                                    if(!TextUtils.isEmpty(constell)) {
                                        F.id(txt_constell).text(constell);
                                    }
                                    String birthday = beanHome.birthday;
                                    if (!TextUtils.isEmpty(birthday)) {
                                        F.id(activity_write_user_data_birthday).text(birthday);
                                    }
                                } else if (state == 1) {
                                    U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.qmsb));
                                } else if (state == 2) {
                                    U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.cscw));
                                }
                            } catch (Exception e) {

                            }
                        } else {
//                U.Toast(MyDataActivity.this, "调用失败");
                        }
                        loadingDalog.dismiss();
                    }
                    else if(action == 0){
                        JSONObject jsonObject = (JSONObject)result;
                        String msgText = jsonObject.getString("MsgText");
                        if("true".equals(msgText)){
                            timeCount = new WriteUserDataActivity.TimeCount(60000, 1000);
                            timeCount.start();
                        }else if("false".equals(msgText)){
                            String state = jsonObject.getString("State");
                            U.Toast(WriteUserDataActivity.this,state);
                        }
                        loadingDalog.dismiss();
                    }
                    else if(action == 4){
                        JSONObject json = (JSONObject)result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.bdcg));
                            F.id(R.id.ll_phone).visibility(View.GONE);
                            F.id(R.id.activity_write_user_data_mobile).getEditText().setFocusable(false);
                            F.id(R.id.activity_write_user_data_mobile).getEditText().setFocusableInTouchMode(false);
                        }else if (state == 1) {
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.cscw));
                        }else if (state == 3) {
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.sjyzmcw));
                        }else if (state == 5) {
                            U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.sjmhycz));
                        }else if (state == 6) {
                            U.Toast(WriteUserDataActivity.this,getResources().getString(R.string.bdsb));
                        } else if (state == 15) {
                            U.Toast(WriteUserDataActivity.this, getResources().getString(R.string.yzmsx));
                        }
                        loadingDalog.dismiss();
                    }
                }else{
                    loadingDalog.dismiss();
                    U.Toast(WriteUserDataActivity.this,"result："+result);
                }

            }catch (Exception e){
                Log.e("完善资料error：",e.getMessage());
            }

        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    //  通过遍历集合获得市的名字 --备用赋值给Spinner1
//    private void getPriovince(){
//        listOne = new ArrayList<String>();
//        for (RegionBean bean : lists) {
//            String cityname = bean.region_name;
//            listOne.add(cityname);
//        }
//    }



    /**
     * 获取个人资料接口
     */
    public void myInfoData() {
        loadingDalog.show();
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.MY_INF0;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }

    //========================================================绑定手机号码===========================================================================================
    /**
     * 获取验证码倒计时
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            F.id(R.id.btn_verify_code).clickable(false);
            timeOut = millisUntilFinished / 1000;
            F.id(R.id.btn_verify_code).text(getResources().getString(R.string.message_has_been_sent)+"(" + timeOut + ")");
        }

        @Override
        public void onFinish() {
            F.id(R.id.btn_verify_code).text(getResources().getString(R.string.to_obtain_the_verification_code));
            F.id(R.id.btn_verify_code).clickable(true);
        }
    }

    public void onStop() {
        super.onStop();
        if (null != timeCount) {
            timeCount.cancel();
        }
    }

    public  class EditChangedListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void afterTextChanged(Editable s) {
           String  code = F.id(R.id.activity_login_phone_code).getText().toString();
            if (code.length()>3){
                setPhoneData(code);
            }
        }
    };

    /**
     * 绑定手机号码
     */
    public void setPhoneData( String  code) {
        loadingDalog.show();

        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.SET_PHONE;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id" + user_id, "code" + code, "new_phone" + phone,"time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("code", code);
            parmaMap.put("new_phone", phone);
            parmaMap.put("time", time);
            parmaMap.put("sign", md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 4);
        } catch (Exception e) {

        }
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
        return format.format(date);
    }

}
